package com.wzu.zlb.ems.controller;

import com.sun.org.apache.xpath.internal.operations.Or;
import com.wzu.zlb.ems.pojo.Design;
import com.wzu.zlb.ems.pojo.Order;
import com.wzu.zlb.ems.pojo.Product;
import com.wzu.zlb.ems.service.OrderService;
import com.wzu.zlb.ems.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class OrderAction {
    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;

    @GetMapping("/orderList")
    public String goToOrderList(HttpSession session,Model model){
        return "orderList";
    }

    @GetMapping("/orderAdd")
    public String goToOrderAdd(HttpSession session,Model model){
        ArrayList<Product> products= (ArrayList<Product>) productService.findAllProduct();
        model.addAttribute("products",products);
        return "orderAdd";
    }

    //展示订单列表接口
    @GetMapping("/order/list")
    public String getOrderList(HttpSession session,Model model){
        List<Order> orders = orderService.findAllOrders();
        model.addAttribute("orders",orders);
        return "orderList";
    }

    //搜索订单
    @GetMapping("/order/search")
    public String searchOrderList(Model model, HttpServletRequest request){
        Order order=new Order();
        String orderId=request.getParameter("orderId");
        String productName=request.getParameter("productName");
        if (orderId.trim().isEmpty()) orderId= String.valueOf(0);
        if (productName.trim().isEmpty()) productName= null;
        order.setOrderId(Integer.valueOf(orderId));
        order.setProductName(productName);
        List<Order> orders = orderService.searchOrders(order);
        model.addAttribute("orders",orders);
        return "orderList";
    }

    //查看订单详情
    @GetMapping("/order/detail/{id}")
    public String getOrderDetail(@PathVariable("id")Integer id,Model model){
        Order order = orderService.findOrderById(id);
        List<Design> designs = productService.findDesignsByProductId(order.getProductId());
        model.addAttribute("order",order);
        model.addAttribute("designs",designs);
        return "orderDetail";
    }

    @PostMapping("/add/search")
    @ResponseBody
    public Map<String ,Object> addToSearch(HttpServletRequest request){
        List<Product> list=productService.findAllProduct();
        Map<String, Object> map=new HashMap<>();
        map.put("status",200);
        map.put("data",list);
        return map;
    }


    //添加订单接口 返回statu：0表示添加成功，1表示插入失败，2表示插入异常
    @PostMapping("/order/add")
    @ResponseBody
    public Map<String,String> addOrder(Order order,HttpSession session,Model model){
        Integer flag = 0;
        Product product= productService.searchProduct(order.getProductName());
        order.setCreatedDate(new Date());
        order.setProductId(product.getProductId());
        order.setStatue(0);
        System.out.println(order.toString());
        Map<String,String> res = new HashMap<>();
        if (order.getStartDate()==null || order.getLimitTime()==null || order.getCustomName().trim().isEmpty() || order.getCustomPhone().trim().isEmpty() || order.getOrderNum()==null){
            res.put("mes","所有带星号都是必填项，必填项没有完全填写！！！");
            res.put("statue","3");
        }else if (order.getStartDate().compareTo(new Date())<0){
            res.put("statue","3");
            res.put("mes","开始时间必须不早于今天！！");
        } else {
            try{
                flag+=orderService.addOrder(order);
                if(flag>=1){
                    res.put("statue","0");
                }else{
                    res.put("statue","1");
                }
            }catch (Exception e){
                res.put("statue","2");
                res.put("err",e.getMessage());
            }
        }
        return res;
    }

    //删除订单接口 返回statu：0表示删除成功，1表示删除失败，2表示删除异常
    @PostMapping("/order/delete/{ids}")
    @ResponseBody
    public Map<String,String> deleteOrder(@PathVariable("ids")String ids){
        Integer flag = 0;
        Map<String,String> res = new HashMap<>();
        try{
            String[] oids = ids.split(",");
            Integer oid;
            for(int i=0;i<oids.length;i++){
                if(oids[i]==null)
                    continue;
                oid= Integer.parseInt(oids[i]);
                flag+=orderService.deleteOrder(oid);
            }
            if(flag==oids.length){
                res.put("statue","0");
            }else{
                res.put("statue","1");
            }
        }catch (Exception e){
            res.put("statue","2");
            res.put("err",e.getMessage());
        }
        return res;
    }

    //添加订单接口 返回statu：0表示修改成功，1表示修改失败，2表示修改异常
    @PostMapping("/order/modify")
    @ResponseBody
    public Map<String,String> modifyOrder(Order order, @RequestParam(value = "orderId") Integer orderId, HttpSession session, Model model){
        Integer flag = 0;
        System.out.println(order.toString());
        if (order.getStatue()==0){
            order.setFinishDate(null);
        }else if (order.getStatue()==1){
            order.setFinishDate(null);
        }else if (order.getStatue()==2){
            order.setFinishDate(new Date());
        }
        order.setOrderId(orderId);
        Map<String,String> res = new HashMap<>();
        try{
            flag+=orderService.modifyOrder(order);
            if(flag>=1){
                res.put("statue","0");
            }else{
                res.put("statue","1");
            }
        }catch (Exception e){
            res.put("statue","2");
            res.put("err",e.getMessage());
        }
        return res;
    }


}
